﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XboxOneDriverApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.Run(new MainForm());
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.ExceptionObject.ToString());


            try
            {
                if (e.ExceptionObject is Exception)
                {
                    SaveException((Exception)e.ExceptionObject);
                }
            }
            catch { }
        }

        static void SaveException(Exception e)
        {
            // Save Log of the Call Stack
            string log = GetLog(e);
            Assembly myAss = Assembly.GetEntryAssembly();
            string dir = Path.GetDirectoryName(myAss.Location);
            DateTime time = DateTime.Now;
            string logLoc = Path.Combine(dir, "Log " + time.Hour + "-" + time.Minute + "-" + time.Second) + ".log";

            using (FileStream stream = new FileStream(logLoc, FileMode.Create))
            {
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(log);
            }
        }

        static string GetLog(Exception ex)
        {
            string log = "";
            Assembly myAss = Assembly.GetEntryAssembly();

            DateTime now = DateTime.Now;

            log += "// Nucleus Exception log";
            log += Environment.NewLine;
            log += now.ToShortDateString();
            log += Environment.NewLine;
            log += now.ToShortTimeString();
            log += Environment.NewLine;

            log += myAss.FullName;
            log += Environment.NewLine;

            log += ex.ToString();
            log += Environment.NewLine;
            log += ex.GetType().FullName;
            log += Environment.NewLine;
            log += ex.GetType().Assembly.FullName;

            return log;
        }
    }
}
